package com.sh.healthtv.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.VideoView;

/**
 * Created by zhouyucheng on 2017/8/4.
 */

public class MyVideoView extends VideoView {
    private VideoStateListener mVideoStateListener;
    private ConnectivityManager connectivityManager;
    private NetworkInfo info;
    private boolean isPlayTv;

    private boolean isSeek;

    public MyVideoView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        Log.i("type1", "MyVideoView  MyVideoView(1)  ");
        init(context);
    }

    public MyVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
        Log.i("type1", "MyVideoView  MyVideoView(2)  ");
        init(context);
    }

    public MyVideoView(Context context) {
        super(context);
        Log.i("type1", "MyVideoView  MyVideoView(3)  ");
        init(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // TODO Auto-generated method stub

        int width = getDefaultSize(0, widthMeasureSpec);
        int height = getDefaultSize(0, heightMeasureSpec);

        setMeasuredDimension(width, height);
    }

    public void setZone(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }

    public static final int SEEKBAR_CHANGE = 1;

    private int myCurrentPosition;

    private Handler mHandler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case SEEKBAR_CHANGE :
                    mHandler.removeMessages(SEEKBAR_CHANGE);
                    isSeek = false;
                    if (isSeek) {
                        myCurrentPosition = MyVideoView.this
                                .getCurrentPosition();
                        if (mVideoStateListener != null) {
                            mVideoStateListener
                                    .OnSeekBarChange(myCurrentPosition);
                        }
                        mHandler.sendEmptyMessageDelayed(SEEKBAR_CHANGE, 1000);

						/*
						 * if(surplus == 15){ if(mVideoStateListener != null){
						 * mVideoStateListener.OnUpcoming(true); } } if(surplus
						 * < 15){ if(mVideoStateListener != null){
						 * mVideoStateListener.OnUpcoming(false); } }
						 */
                    }
                    break;

                default :
                    break;
            }
        };
    };

    public void terminate() {
        cancelBgTimer();
        this.stopPlayback();
        Log.i("type2", "MyVideoView  terminate()  ");
    };

    public void unListener() {
        mVideoStateListener = null;
    }

    public void init(Context context) {
        this.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                if (mVideoStateListener != null) {
                    mHandler.sendEmptyMessage(SEEKBAR_CHANGE);
                    mVideoStateListener.OnPrepared(mp);
                    setCheckUpdateRepeatTask();
                }
            }
        });

        this.setOnInfoListener(new MediaPlayer.OnInfoListener() {

            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                switch (what) {
                    case MediaPlayer.MEDIA_INFO_BUFFERING_START :
                        if (mVideoStateListener != null) {
                            mVideoStateListener.OnBufferingStart();
                        }
                        break;
                    case MediaPlayer.MEDIA_INFO_BUFFERING_END :
                        if (mVideoStateListener != null) {
                            mVideoStateListener.OnBufferingEnd();
                        }
                        break;
                    default :
                        break;
                }
                return false;
            }
        });

        this.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                if (mVideoStateListener != null) {
                    mVideoStateListener.OnComPletion(mp);
                }
                cancelBgTimer();
            }

        });

        this.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                if (mVideoStateListener != null) {
                    mVideoStateListener.OnError(mp, what, extra);
                }
                cancelBgTimer();
                return true;
            }
        });
        OperateVideoView.getInstance().setVideo(MyVideoView.this);
    };

    public void setListener(boolean isLive, VideoStateListener lien) {
        this.mVideoStateListener = lien;
        this.isPlayTv = isLive;
    }

    public VideoStateListener getListener() {
        return mVideoStateListener;
    }

    public interface VideoStateListener {

        void OnPrepared(MediaPlayer mp);

        void OnSeekBarChange(int progress);

        void OnBufferingStart();

        void OnBufferingEnd();

        void OnUpcoming(boolean isGetNextEpg);

        void OnComPletion(MediaPlayer mp);

        void OnError(MediaPlayer mp, int what, int extra);

        void OnNetWorkChange(boolean isConnect);
    }

    public void registeResever(Context context) {
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(connectChangeReceiver, mFilter);
    }

    public void unRegisteResever(Context context) {
        if (connectChangeReceiver != null && context != null) {
            context.unregisterReceiver(connectChangeReceiver);
        }
    }

    private BroadcastReceiver connectChangeReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                info = connectivityManager.getActiveNetworkInfo();
                if (info != null && info.isAvailable()) {
                    mVideoStateListener.OnNetWorkChange(true);
                } else {
                    mVideoStateListener.OnNetWorkChange(false);
                }
            }
        }
    };

    private void setCheckUpdateRepeatTask() {
        if (isPlayTv) {
            return;
        } else {
            isSeek = true;
        }
        mHandler.sendEmptyMessageDelayed(SEEKBAR_CHANGE, 100);
    }

    public void cancelBgTimer() {
        mHandler.removeMessages(SEEKBAR_CHANGE);
        isSeek = false;
    }
}
